﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace projetCsharp
{
    public partial class Form1 : Form
    {
        private Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        static ManualResetEvent _clientDone = new ManualResetEvent(false);

        public Form1()
        {
            InitializeComponent();

        }

        private void connexion()
        {
            byte ip1 = Convert.ToByte(txtIp1.Text);
            byte ip2 = Convert.ToByte(txtIp2.Text);
            byte ip3 = Convert.ToByte(txtIp3.Text);
            byte ip4 = Convert.ToByte(txtIp4.Text);
            Byte[] Ipadress = new Byte[4];
            Ipadress[0] = ip1;
            Ipadress[1] = ip2;
            Ipadress[2] = ip3;
            Ipadress[3] = ip4;

            IPAddress ip = new IPAddress(Ipadress);
            try
            {
                sck.Connect(ip, Convert.ToInt32(txtPort.Text));
                lblEtatConnexion.Text = "Connection établie";
            }
            catch (Exception e)
            {
                lblEtatConnexion.Text = e.Message.ToString();
            }
        }

        public string Receive()
        {
            string response = "Operation Timeout";

            // We are receiving over an established socket connection
            if (sck != null)
            {
                // Create SocketAsyncEventArgs context object
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = sck.RemoteEndPoint;

                // Setup the buffer to receive the data
                socketEventArg.SetBuffer(new Byte[50], 0, 50);

                // Inline event handler for the Completed event.
                // Note: This even handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                {
                    if (e.SocketError == SocketError.Success)
                    {
                        // Retrieve the data from the buffer
                        response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                        response = response.Trim('\0');
                    }
                    else
                    {
                        response = e.SocketError.ToString();
                    }

                    _clientDone.Set();
                });

                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone.Reset();

                // Make an asynchronous Receive request over the socket
                sck.ReceiveAsync(socketEventArg);

                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone.WaitOne(5);
            }
            else
            {
                response = "Socket is not initialized";
            }

            return response;
        }

        /// <summary>
        /// Closes the Socket connection and releases all associated resources
        /// </summary>
        public void Close()
        {
            if (sck != null)
            {
                sck.Close();
                lblEtatConnexion.Text = "Déconnecté";
            }
        }

        public string Send(string data)
        {
            string response = "Operation Timeout";

            // We are re-using the socket object that was initialized in the Connect method
            if (sck != null)
            {
                // Create SocketAsyncEventArgs context object
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

                // Set properties on context object
                socketEventArg.RemoteEndPoint = sck.RemoteEndPoint;
                socketEventArg.UserToken = null;

                // Inline event handler for the Completed event.
                // Note: This event handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                {
                    response = e.SocketError.ToString();

                    // Unblock the UI thread
                    _clientDone.Set();
                });

                // Add the data to be sent into the buffer
                byte[] payload = Encoding.UTF8.GetBytes(data);
                socketEventArg.SetBuffer(payload, 0, payload.Length);

                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone.Reset();

                // Make an asynchronous Send request over the socket
                sck.SendAsync(socketEventArg);

                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone.WaitOne(500);
            }
            else
            {
                response = "Socket is not initialized";
            }

            return response;
        }

        private void btnEcrire_Click(object sender, EventArgs e)
        {
            try
            {
                if (!sck.Connected)
                    connexion();
                Send(rtxtZoneEcriture.Text);
                rtxtZoneLecture.Text += Receive();
                Close();
            }
            catch (Exception e1)
            {
                lblEtatConnexion.Text = e1.Message.ToString();
            }
        }

        private void btnConnexion_Click(object sender, EventArgs e)
        {
            connexion();
        }
    }
}
